package cn.edu.whu.forecast.schudule.crawl;

import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

public class DownLoadPicFromUrlUtil {
    //链接url下载图片
    public static void downloadPicture(String imageUrl, String root, String fileName) {

        File file =new File(root);

        //如果文件夹不存在则创建

        if (!file .exists() && !file .isDirectory()) file .mkdir();

        URL url;
        try {
            url = new URL(imageUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(root+"//"+fileName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串
            System.out.println(encode);
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void clearWaterMark(String root, String fileName) throws IOException {
        String path = root+"//"+fileName;
        BufferedImage bi = ImageIO.read(new File(path));
        //水印替换成白色
        Color disColor = new Color(255, 255, 255);
        for (int i = 0; i < bi.getWidth(); i++) {
            for (int j = 0; j < bi.getHeight(); j++) {
                int color = bi.getRGB(i, j);
                Color oriColor = new Color(color);
                int red = oriColor.getRed();
                int greed = oriColor.getGreen();
                int blue = oriColor.getBlue();
                //245,245,245是灰色  这里是把当前像素点由灰色替换成白色
                if (red == 245 && greed == 245 && blue == 245) {
                    bi.setRGB(i, j, disColor .getRGB());
                }
            }
        }
        String type = path.substring(path.lastIndexOf(".") + 1, path.length());
        Iterator<ImageWriter> it = ImageIO.getImageWritersByFormatName(type);
        ImageWriter writer = it.next();
        File f = new File(root);
        f.getParentFile().mkdirs();
        ImageOutputStream ios = ImageIO.createImageOutputStream(f);
        writer.setOutput(ios);
        writer.write(bi);
        bi.flush();
        ios.flush();
        ios.close();
    }
}
